package lion.framework.core.task.cluster;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 集群实例守护者，每隔1秒钟更新一下集群实例的状态，如果5秒钟未更新，则其他实例认为该集群实例已经宕掉了，其他实例将会接替该实例的任务
 *
 * <pre>
 * time   2013年7月25日
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class ClusterInstanceGuard extends TimerTask {

	private AtomicBoolean start = new AtomicBoolean(false);

	private Map<String, ClusterInstance> clusterInstances;;

	public ClusterInstanceGuard(Map<String, ClusterInstance> clusterInstances) {

		this.clusterInstances = clusterInstances;
	}

	public void start() {

		if (start.get()) { return; }
		start.getAndSet(true);

		Timer timer = new Timer("cluster-instance-checker", true);
		timer.scheduleAtFixedRate(this, 0, 1000);
	}

	@Override
	public void run() {

		if (clusterInstances.isEmpty()) { return; }
		for (ClusterInstance instance : clusterInstances.values()) {
			instance.updateStatus();
		}
	}
}
